//
//  RegistViewController.m
//  Baymax
//
//  Created by jolin on 16/4/19.
//  Copyright © 2016年 jolin. All rights reserved.
//

#import "RegistViewController.h"
#import "BMNavBar.h"
#import "Header.h"
#import "RequestAPI.h"
#import "UserInfo.h"
#import <SMS_SDK/SMSSDK.h>

@interface RegistViewController () {
    UITextField *_phoneTF;
    UITextField *_testCodeTF;
    UITextField *_pswTF;
    UITextField *_rePswTF;
    UIButton    *_getTestCodeBtn;
}

@end

@implementation RegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    BMNavBar *loginNav = [[BMNavBar alloc]initWithItems:@[@"返回",@"注册"] navBarStyle:NavBarStyleDefault];
    [self.view addSubview:loginNav];
    [loginNav setItemBlock:^(NSInteger index, id item) {
        //NSLog(@"%ld",index);
        if (0 == index) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    
    //初始化view
    [self initView];
}
#pragma mark - 初始化视图
- (void)initView {
    UITextField *phoneTF = [[UITextField alloc]initWithFrame:CGRectMake(0, 300, MAINFRAME.size.width, 40)];
    phoneTF.placeholder = @"请输入手机号码";
    phoneTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:phoneTF];
    _phoneTF = phoneTF;
    
    UITextField *testCodeTF = [[UITextField alloc]initWithFrame:CGRectMake(0, 341, MAINFRAME.size.width - 200, 40)];
    testCodeTF.placeholder = @"请输入验证码";
    testCodeTF.keyboardType = UIKeyboardTypeNumberPad;
    testCodeTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:testCodeTF];
    _testCodeTF = testCodeTF;
    
    UIButton *getTestCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    getTestCodeBtn.frame = CGRectMake(MAINFRAME.size.width - 190, 351, 190, 30);
    [getTestCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    getTestCodeBtn.backgroundColor = [UIColor blueColor];
    [getTestCodeBtn addTarget:self action:@selector(getTestCode:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:getTestCodeBtn];
    _getTestCodeBtn = getTestCodeBtn;
    
    UITextField *pswTF = [[UITextField alloc]initWithFrame:CGRectMake(0, 382, MAINFRAME.size.width, 40)];
    pswTF.placeholder = @"请输入密码";
    pswTF.secureTextEntry = YES;
    pswTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:pswTF];
    _pswTF = pswTF;
    
    UITextField *rePswTF = [[UITextField alloc]initWithFrame:CGRectMake(0, 423, MAINFRAME.size.width, 40)];
    rePswTF.placeholder = @"请再次输入密码";
    rePswTF.secureTextEntry = YES;
    rePswTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:rePswTF];
    _rePswTF = rePswTF;
    
    UIButton *registBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registBtn.frame = CGRectMake(10, 480, MAINFRAME.size.width - 20, 30);
    [registBtn setTitle:@"注册" forState:UIControlStateNormal];
    registBtn.backgroundColor = [UIColor blueColor];
    [registBtn addTarget:self action:@selector(registUser:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registBtn];
    
}
#pragma mark - 键盘下去事件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
#pragma mark - 获取验证码
- (void)getTestCode:(UIButton *)sender {
    if ([_phoneTF.text isEqualToString:@""]) {
        [CommenTools alertPromptWithView:self.view prompt:@"请填写手机号"];
        return;
    }
    //检查手机号码是否正确
    if (![CommenTools validateMobile:_phoneTF.text]) {
        [CommenTools alertPromptWithView:self.view prompt:@"号码不正确"];
        return;
    }
    //检查网络状态 如果网络通 就改变button的状态 倒计时
    if (REACHSTATUES != 0) {
       // NSLog(@"%ld",[AFNetworkReachabilityManager sharedManager].networkReachabilityStatus);
        //发送校验码
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:@"15014059008"
                                       zone:@"86"
                           customIdentifier:nil
                                     result:^(NSError *error){
                                         if (!error) {
                                             NSLog(@"获取验证码成功");
                                         } else {
                                             NSLog(@"错误信息：%@",error);
                                         }
                                     }];
        //开启定时器
        dispatch_async(dispatch_get_main_queue(), ^{
            NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(waitTestCode:) userInfo:nil repeats:YES];
            [timer fire];
        });
        }else {
       [CommenTools alertPromptWithView:self.view prompt:@"网络未连接"];
    }
    
}
#pragma mark - 倒计时方法
- (void)waitTestCode:(NSTimer *)timer {
    //改变button的title
    static NSInteger count = 60;
    
    if (count == 0) {
        [timer invalidate];
        timer = nil;
        [_getTestCodeBtn setTitle:@"重新发送" forState:UIControlStateNormal];
        _getTestCodeBtn.backgroundColor = [UIColor blueColor];
        _getTestCodeBtn.userInteractionEnabled = YES;
        count = 60;
    }else {
        [_getTestCodeBtn setTitle:[NSString stringWithFormat:@"(%ld)秒",count--] forState:UIControlStateNormal];
        _getTestCodeBtn.backgroundColor = [UIColor lightGrayColor];
        _getTestCodeBtn.userInteractionEnabled = NO;
    }
    NSLog(@"%ld",count);
}
#pragma mark - 检查表单
- (BOOL)validateTextField {
    __block BOOL result = YES;
    if ([_phoneTF.text isEqualToString:@""]) {
        [CommenTools alertPromptWithView:self.view prompt:@"请填写手机号"];
        return !result;
    }
    if ([_testCodeTF.text isEqualToString:@""]) {
        [CommenTools alertPromptWithView:self.view prompt:@"请填写验证码"];
        return !result;
    }
    if ([_pswTF.text isEqualToString:@""]) {
        [CommenTools alertPromptWithView:self.view prompt:@"请填写密码"];
        return !result;
    }
    if (![_pswTF.text isEqualToString:_rePswTF.text]) {
        [CommenTools alertPromptWithView:self.view prompt:@"两次密码不一致"];
        return !result;
    }
    //检查手机号码是否正确
    if (![CommenTools validateMobile:_phoneTF.text]) {
        [CommenTools alertPromptWithView:self.view prompt:@"号码不正确"];
        return !result;
    }
    if (REACHSTATUES == 0) {
        [CommenTools alertPromptWithView:self.view prompt:@"网络未连接"];
        return !result;
    }
    [SMSSDK commitVerificationCode:_testCodeTF.text phoneNumber:_phoneTF.text zone:@"86" result:^(NSError *error) {
        if (!error) {
            NSLog(@"验证成功");
        }
        else
        {
            NSLog(@"错误信息:%@",error);
            result = NO;
        }
    }];
    return result;
}
#pragma mark - 注册
- (void)registUser:(UIButton *)sender {
    //验证成功
    if ([self validateTextField]) {
        //发送注册请求
        NSDictionary *userDic = @{@"phone":_phoneTF.text, @"password":_pswTF.text};
        UserInfo *user = [[UserInfo alloc]initWithDic:userDic];
        
        RequestAPI *req = [[RequestAPI alloc]init];
        [req userRegistWithUserInfo:user];
        
    }else {
        return;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
